'''
Created on 23.02.2011

@author: public
'''
import urllib
import urllib2
import const
import logging
import sys
import util

__logger = logging.getLogger('auth')

def authorize (url, user, psw):
    __logger.debug('authorize(%s, %s)' % (url, user,))
    
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
    
    try :
        urllib2.install_opener(opener)

        params = urllib.urlencode(
                    {
                     'login_username' : user, 
                     'login_password': psw,
                     'login':'qwe',       
                     }
                )

        f = opener.open(url, params)
        f.close()
        
        opener.needsReauth = False
        __logger.debug('authorization is successful')
    except:
        opener.needsReauth = 1
        __logger.debug('*** authorization problem: %s' % sys.exc_info()[1])
        
    return opener

def checkOpener(opener, url, loggedOutToken):
    '''Checks opener for validity respectively to authorization.
    If loaded file contains 'logged out' token - sets opener.needsReauth = 1.
    '''
    __logger.debug('checking opener')

    try :    
        webFile = opener.open(url, timeout=300)
    
        __logger.debug('opened')
            
        contents = webFile.read()
        
        __logger.debug('read')
            
        webFile.close()
                
        if (contents.rfind(loggedOutToken) != -1):
            __logger.debug('@@@ logged out token found. Seems the re-authorization is needed')
            opener.needsReauth = 1
            return
        else :            
            __logger.debug('opener is still valid')
            return            
    except:        
        __logger.debug('*** opener checking problem: %s' % (sys.exc_info()[1], ))  


if __name__ == '__main__':
    logging.config.fileConfig('../' + const.LOGGING_CFG_FILE)
       
    user = util.readConfigProperty('auth', 'user')
    psw = util.readConfigProperty('auth', 'psw')
    url = util.readConfigProperty('auth', 'url')
    
    opener = authorize(url, user, psw)
    
    values = {'bb_dl' : '3155870'}
    
    data = urllib.urlencode(values)
    
    f = opener.open('http://dl.rutracker.org/forum/dl.php?t=3155870', data)
    contents = f.read()    
    f.close()
        
    print contents    
